package com.estronger.shopmanage.ui.batchpg;

import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.estronger.pull_to_refresh_expandablelist.CommonFooterView;
import com.estronger.pull_to_refresh_expandablelist.PullToRefreshBase;
import com.estronger.pull_to_refresh_expandablelist.PullToRefreshListView;
import com.estronger.shopmanage.R;
import com.estronger.shopmanage.adapter.batchpg.BatchPgListAdapter;
import com.estronger.shopmanage.base.BaseActivity;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.ReturnMsgEntity;
import com.estronger.shopmanage.bean.batch.BatchPgListBean;
import com.estronger.shopmanage.bean.batch.DeliverPGListData;
import com.estronger.shopmanage.bean.batch.InstallPGListData;
import com.estronger.shopmanage.bean.batch.MeasurePGListData;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.utils.JsonUtil;
import com.estronger.shopmanage.utils.NetUtils;
import com.estronger.shopmanage.utils.Toast;
import com.estronger.shopmanage.view.CircularProgress;
import com.lidroid.xutils.http.RequestParams;
import com.soonfor.evaluate.tools.NoDoubleClickUtils;


import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Soonfor on 2017/5/17.
 * 批量派工
 */

public class BatchPgActivity extends BaseActivity
        implements PullToRefreshBase.OnRefreshListener<ListView>, View.OnClickListener, BatchPgListAdapter.AdapterListener {

    public static boolean isNeedUpdateView = false;//返回界面时是否需要刷新界面
    private boolean isPgSuccess = false;//是否有批量派工成功过
    private RelativeLayout rl_root;// 根布局view
    private Activity mContext;
    private LinearLayout ll_checkall;//全选
    private ImageView iv_checkall;//全选
    private PullToRefreshListView mListView;
    private CircularProgress bar;
    private TextView empty_view;
    private Button btn_pg_goto;//去派工
    private ArrayList<BatchPgListBean> dataList;
    private BatchPgListAdapter bpAdapter;
    private int dataType = 0; //1-测量 2-送货 3-安装
    private int pageIndex = 1; //当前页码
    private int pageSize = 10;
    private int pageCount = 0;//总页数

    // 初始化各个View
    @Override
    protected void initView() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        rl_root = (RelativeLayout) View.inflate(this,
                R.layout.activity_pg_batch, null);
        setContentView(rl_root);
        mContext = BatchPgActivity.this;
        ll_checkall = rl_root.findViewById(R.id.ll_checkall);
        iv_checkall = rl_root.findViewById(R.id.iv_checkall);
        mListView = (PullToRefreshListView) rl_root.findViewById(R.id.success_listview);
        bar = (CircularProgress) rl_root.findViewById(R.id.loding_view);
        empty_view = (TextView) rl_root.findViewById(R.id.empty_view);
        btn_pg_goto = rl_root.findViewById(R.id.btn_pg_goto);
        ll_checkall.setOnClickListener(this);
        btn_pg_goto.setOnClickListener(this);
        mListView.setOnRefreshListener(this);
        mListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        mListView.setState(CommonFooterView.State.HIDE);
        //获得数据
        bpAdapter = new BatchPgListAdapter(mContext);
        bpAdapter.setAdapterListener(this);
        mListView.setAdapter(bpAdapter);
        bar.setVisibility(View.VISIBLE);
        dataType = getIntent().getIntExtra("data_type", 0);
        isPgSuccess = false;
        isNeedUpdateView = false;
        iv_checkall.setTag(0);
        pageIndex = 1;
        loadData(1);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(isNeedUpdateView){
            isPgSuccess = true;
            if (null != bar) bar.setVisibility(View.VISIBLE);
            pageIndex = 1;
            loadData(1);
        }
        isNeedUpdateView = false;
    }

    //加载数据
    protected void loadData(final int pageNo) {
        if (!NetUtils.isNetworkConnected(this)) {
            Toast.show(this, "网络链接已断开！", 2000);
        } else {
            MyApplication.getHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    postRequest(pageNo);
                }
            }, 100);
        }
    }

    //请求
    public void postRequest(int pageNo) {
        RequestParams params = new RequestParams();
        params.addBodyParameter("usercode", MyApplication.getUserCode());
        params.addBodyParameter("gettype", "0");
        params.addBodyParameter("pagesize", pageSize + "");
        params.addBodyParameter("pageindex", String.valueOf(pageNo));
        if (dataType == 1) {
            //测量任务待派工
            params.addBodyParameter("sf_action", "getassignlist");
        } else if (dataType == 2) {
            //送货任务待派工
            params.addBodyParameter("sf_action", "getdlvassignlist");
        } else if (dataType == 3) {
            //安装任务待派工
            params.addBodyParameter("sf_action", "getistassignlist");
        }
        connect(params, NetManager.GETLIST_PG_DATAS);
    }

    @Override
    protected void onNetErorr(int code, String msg) {
        if (null != mListView) {
            mListView.setState(CommonFooterView.State.HIDE);
            if (null != bar) bar.setVisibility(View.GONE);
            mListView.onRefreshComplete();
            if (dataList.size() == 0) {
                empty_view.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    protected void onNetSuccess(int code, String result) {
        try {
            if (null != mListView) {
                mListView.setState(CommonFooterView.State.HIDE);
                mListView.onRefreshComplete();
                if (code == NetManager.GETLIST_PG_DATAS) {
                    List<BatchPgListBean> resultList = new ArrayList<>();
                    String msg = "暂无待派工数据";
                    try {
                        ReturnMsgEntity re = JsonUtil.returnMsgEntity(result);
                        if(re.getMsgcode() == 0 && re.getDataJson() != null) {
                            JSONObject jo = new JSONObject(re.getDataJson());
                            if(jo.has("pageindex")){
                                pageIndex = jo.getInt("pageindex");
                                int total = 1;
                                if(jo.has("total")){
                                    total = jo.getInt("total");
                                }
                                pageCount = JsonUtil.getPageCount(pageSize, total);
                            }
                            if(jo.has("list")) {
                                JSONArray ja = new JSONArray(jo.getString("list"));
                                if (ja!=null && ja.length() > 0) {
                                    if (dataType == 1) {
                                        for (int i = 0; i < ja.length(); i++) {
                                            BatchPgListBean listBean = new BatchPgListBean();
                                            listBean.setDatatype(1);
                                            MeasurePGListData measurePGListData = gson.fromJson(ja.getString(i), MeasurePGListData.class);
                                            listBean.setFcheck(1);
                                            listBean.setMeasure(measurePGListData);
                                            resultList.add(listBean);
                                        }
                                    } else if (dataType == 2) {
                                        for (int i = 0; i < ja.length(); i++) {
                                            BatchPgListBean listBean = new BatchPgListBean();
                                            listBean.setDatatype(2);
                                            DeliverPGListData deliverPGListData = gson.fromJson(ja.getString(i), DeliverPGListData.class);
                                            listBean.setFcheck(1);
                                            listBean.setDeliver(deliverPGListData);
                                            resultList.add(listBean);
                                        }
                                    } else if (dataType == 3) {
                                        for (int i = 0; i < ja.length(); i++) {
                                            BatchPgListBean listBean = new BatchPgListBean();
                                            listBean.setDatatype(3);
                                            InstallPGListData installPGListData = gson.fromJson(ja.getString(i), InstallPGListData.class);
                                            listBean.setFcheck(1);
                                            listBean.setInstall(installPGListData);
                                            resultList.add(listBean);
                                        }
                                    }
                                }
                            }
                        } else {
                            if (re != null) msg = re.getMsg();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        msg = e.getMessage();
                    }
                    if (resultList.size() > 0) {
                        empty_view.setVisibility(View.GONE);
                        if (pageIndex == 1) {
                            if (dataList == null) dataList = new ArrayList<>();
                            else dataList.clear();
                            iv_checkall.setTag(1);
                            iv_checkall.setImageResource(R.drawable.checked);
                        }
                        dataList.addAll(resultList);
                        if (dataList.size() >= pageSize) {
                            mListView.setMode(PullToRefreshBase.Mode.BOTH);
                        }
                    } else {
                        if (pageIndex == 1) {
                            if (dataList == null) dataList = new ArrayList<>();
                            else dataList.clear();
                            empty_view.setVisibility(View.VISIBLE);
                            empty_view.setText(msg);
                        }
                        Toast.show(mContext, msg, Toast.LENGTH_SHORT);
                    }
                    if(pageIndex == 1 && dataList.size()>0){
                        mListView.mRefreshableView.smoothScrollByOffset(0);
                    }
                    bpAdapter.notifyDataSetChanged(dataList);
                }
            }
        } catch (Exception ee) {
            ee.fillInStackTrace();
            if (pageIndex == 1) {
                if (dataList == null) dataList = new ArrayList<>();
                else dataList.clear();
                empty_view.setVisibility(View.VISIBLE);
                empty_view.setText(ee.getMessage());
            }
            Toast.show(mContext, ee.getMessage(), Toast.LENGTH_SHORT);
        }
        if (null != bar) bar.setVisibility(View.GONE);
    }


    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        if (mListView.isHeaderShown()) {
            pageIndex = 1;
            loadData(1);
        } else if (mListView.isFooterShown()) {
            if(pageIndex >= pageCount){
                Toast.show(mContext, "~没有更多啦~", Toast.LENGTH_SHORT);
            }else {
                loadData(pageIndex + 1);
            }
        }
        mListView.postDelayed(new Runnable() {
            @Override
            public void run() {
                mListView.onRefreshComplete();
            }
        }, 1000);
    }

    //勾选监听
    @Override
    public void onCheckChange(boolean isCheckedAll) {
        if (isCheckedAll) {
            iv_checkall.setImageResource(R.drawable.checked);
        } else {
            iv_checkall.setImageResource(R.drawable.confirm_check_bt);
        }
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.ll_checkall) {
            try {
                int checkcode = (int) iv_checkall.getTag();
                if (checkcode == 0) {
                    if (dataList != null && dataList.size() > 0) {
                        for (int i = 0; i < dataList.size(); i++) {
                            dataList.get(i).setFcheck(1);
                        }
                        if (bpAdapter != null) {
                            bpAdapter.notifyDataSetChanged(dataList);
                            iv_checkall.setTag(1);
                            iv_checkall.setImageResource(R.drawable.checked);
                        }
                    }
                } else {
                    if (dataList != null && dataList.size() > 0) {
                        for (int i = 0; i < dataList.size(); i++) {
                            dataList.get(i).setFcheck(0);
                        }
                        if (bpAdapter != null) {
                            bpAdapter.notifyDataSetChanged(dataList);
                            iv_checkall.setTag(0);
                            iv_checkall.setImageResource(R.drawable.confirm_check_bt);
                        }
                    }
                }
            }catch (Exception e){
                e.fillInStackTrace();
            }
        } else if (v.getId() == R.id.btn_pg_goto) {//去派工
            if (NoDoubleClickUtils.isDoubleClick()) return;
            String ids = "";
            for (BatchPgListBean listBean : dataList){
                if(listBean.getFcheck() == 1){
                    if(listBean.getDatatype() == 1) {
                        ids += listBean.getMeasure().getMeasureid() + ",";
                    }else if(listBean.getDatatype() == 2) {
                        ids += listBean.getDeliver().getDlvid() + ",";
                    }else if(listBean.getDatatype() == 3) {
                        ids += listBean.getInstall().getDlvid() + ",";
                    }
                }
            }
            if(ids.endsWith(",")){
                ids = ids.substring(0, ids.length()-1).trim();
            }
            if(ids.equals("")){
                Toast.show(mContext, "请至少选择一条数据进行派工", Toast.LENGTH_SHORT);
            }else {
                BatchPgConfirmActivity.startTActivity(mContext, dataType, ids);
            }
        }
    }

    @Override
    public void onBackPressed() {
        if(isPgSuccess){
            Intent intent = new Intent();
            intent.putExtra("data_update", 1);
            setResult(Activity.RESULT_OK);
            finish();
        }else {
            finish();
        }
    }

    @Override
    public void onBackViewClick(View view) {
        if(isPgSuccess){
            Intent intent = new Intent();
            intent.putExtra("data_update", 1);
            setResult(Activity.RESULT_OK);
            finish();
        }else {
            finish();
        }
    }

    /**
     * @param activity
     * @param dataType 1-测量 2-送货 3-安装
     *                 //     * @param id
     */
    public static void startTActivity(Activity activity, int dataType, int requestCode) {
        Intent intent = new Intent(activity, BatchPgActivity.class);
        intent.putExtra("data_type", dataType);
//        intent.putExtra("data_id", id);
        activity.startActivityForResult(intent, requestCode);
    }
}
